#include<iostream>
#include<string>
#include<unistd.h>
#include<cstring>
#include<cassert>
#include<sys/types.h>
int main()
{
    //创建管道
    int pipefd[2] = {0};
    int sign = pipe(pipefd);
    if(sign == -1)
    {
        std::cout << "pipe error" << errno << strerror(errno) <<std::endl;
    }
    std::cout << pipefd[0] << std::endl;
    std::cout << pipefd[1] << std::endl;
    //创建子进程
    pid_t son = fork();
    assert(!(son == -1));
    if(son == 0)
    {
        //关闭不需要的fd，让父进程读，子进程写
        close(pipefd[0]);
        //开始通信
        std::string str = "hello，我是子进程";
        int cnt =1;
        char buffer[1024] = {0};
        while(1)
        {
            snprintf(buffer,sizeof(buffer),"计数器为%d 我的pid为%d 发送的消息为%s",cnt++,getpid(),str.c_str());
            write(pipefd[1],buffer,strlen(buffer));
            sleep(1);
        }
        close(pipefd[1]);
        exit(0);
    }
    //父进程
    close(pipefd[1]);
    //开始通信
    char buffer[1024] = {0};
    while(1)
    {
        int signal = read(pipefd[0],buffer,sizeof(buffer)-1);
        if(signal > 0)
        {
            std::cout << "我是父进程 我收到了子进程的消息" << buffer <<std::endl;
            buffer[signal] = 0;
        }

        sleep(1);
    }
    close(pipefd[0]);
    return 0;
}